<?php
/**
 * 测试查询性能
 * 分析列表加载慢的原因
 */

namespace think\admin;

use think\App;

define('ROOT_PATH', __DIR__ . DIRECTORY_SEPARATOR);
require __DIR__ . '/vendor/autoload.php';

// 创建应用实例
$app = new App();
$app->initialize();

// 开启SQL日志监听
\think\facade\Db::listen(function ($sql, $time, $master) {
    echo sprintf("[%s] [%.2fms] %s\n", $master ? 'WRITE' : 'READ', $time * 1000, $sql);
});

echo "=== 测试兑换记录列表查询性能 ===\n\n";

$startTime = microtime(true);

// 模拟控制器查询
$query = \app\checkin\model\ExchangeRecord::mk()
    ->with([
        'member',
        'store',
        'operator'
    ])
    ->order('id desc')
    ->limit(20);

$list = $query->select()->toArray();

$endTime = microtime(true);
$totalTime = ($endTime - $startTime) * 1000;

echo "\n=== 查询结果 ===\n";
echo "记录数：" . count($list) . "\n";
echo "总耗时：" . number_format($totalTime, 2) . "ms\n";

echo "\n=== 测试打卡记录列表查询性能 ===\n\n";

$startTime = microtime(true);

$query2 = \app\checkin\model\CheckinRecord::mk()
    ->with([
        'member',
        'store'
    ])
    ->order('id desc')
    ->limit(20);

$list2 = $query2->select()->toArray();

$endTime = microtime(true);
$totalTime2 = ($endTime - $startTime) * 1000;

echo "\n=== 查询结果 ===\n";
echo "记录数：" . count($list2) . "\n";
echo "总耗时：" . number_format($totalTime2, 2) . "ms\n";

echo "\n=== 测试会员列表查询性能 ===\n\n";

$startTime = microtime(true);

$query3 = \app\checkin\model\Member::mk()
    ->with(['registerStore'])
    ->order('id desc')
    ->limit(20);

$list3 = $query3->select()->toArray();

$endTime = microtime(true);
$totalTime3 = ($endTime - $startTime) * 1000;

echo "\n=== 查询结果 ===\n";
echo "记录数：" . count($list3) . "\n";
echo "总耗时：" . number_format($totalTime3, 2) . "ms\n";

echo "\n=== 网络延迟分析 ===\n";
echo "数据库服务器：113.44.136.17\n";
echo "Ping平均延迟：~72ms\n";
echo "预估单次查询延迟：50-150ms\n";
echo "列表页面查询次数：3-5次\n";
echo "预估总延迟：150-750ms\n";

echo "\n=== 优化建议 ===\n";
echo "1. 使用本地数据库（最有效）\n";
echo "2. 启用Redis缓存\n";
echo "3. 添加数据库索引\n";
echo "4. 减少关联查询\n";
echo "5. 使用数据库连接池\n";

